<template>
  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('order.member_info')">
          <el-input v-model="searchForm.search" :placeholder="$t('order.input_nickname_phone_id')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('order.order_number')"><el-input size="small" v-model="searchForm.orderNo"
            :placeholder="$t('order.input_order_number')"></el-input></el-form-item>
        <el-form-item :label="$t('order.order_type')">
          <el-select size="small" v-model="searchForm.orderSource" :placeholder="$t('order.please_select')" clearable>
            <el-option :label="$t('order.all')" value=""></el-option>
            <el-option v-for="(item, index) in orderSourceList" :key="index" :label="item.name"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.delivery_method')">
          <el-select size="small" v-model="searchForm.style_id" :placeholder="$t('order.please_select')">
            <el-option :label="$t('order.all')" value=""></el-option>
            <el-option v-for="(item, index) in exStyle" :key="index" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.merchant_name0')">
          <el-select size="small" v-model="searchForm.shopSupplierId" filterable
            :placeholder="$t('order.please_select')">
            <el-option :label="$t('order.all')" :value="0"></el-option>
            <el-option v-for="(item, index) in supplierList" :key="index" :label="item.name"
              :value="item.shopSupplierId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('order.start_time')">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker size="small" v-model="searchForm.createTime" type="daterange" value-format="YYYY-MM-DD"
              :range-separator="$t('order.to')" :start-placeholder="$t('order.start_date')"
              :end-placeholder="$t('order.end_date')"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item><el-button size="small" type="primary" icon="Search" @click="onSubmit">{{ $t('order.search')
        }}</el-button></el-form-item>
        <el-form-item><el-button size="small" type="success" @click="onExport" v-auth="'/order/operate/export'">{{
          $t('order.export') }}</el-button></el-form-item>
      </el-form>
    </div>
    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-tabs v-model="activeName" @tab-change="handleClick">
          <el-tab-pane :label="$t('order.all_orders')" name="all"></el-tab-pane>
          <el-tab-pane :label="$t('order.unpaid_label') + order_count.payment + ')'" name="payment"></el-tab-pane>
          <el-tab-pane :label="$t('order.to_ship_label') + order_count.delivery + ')'" name="delivery"></el-tab-pane>
          <el-tab-pane :label="$t('order.to_receive_label') + order_count.received + ')'" name="received"></el-tab-pane>
          <el-tab-pane :label="$t('order.to_review_label') + order_count.comment + ')'" name="comment"></el-tab-pane>
          <el-tab-pane :label="$t('order.completed_label') + order_count.six + ')'" name="six"></el-tab-pane>
          <el-tab-pane :label="$t('order.cancelled_label') + order_count.cancel + ')'" name="cancel"></el-tab-pane>
          <el-tab-pane :label="$t('order.cancel_requesting_label') + order_count.cancelApply + ')'"
            name="cancelApply"></el-tab-pane>
          <el-tab-pane :label="$t('order.deleted_prefix') + order_count.delete + ')'" name="delete"></el-tab-pane>
        </el-tabs>
        <el-table size="small" :data="tableData.data" :span-method="arraySpanMethod" border style="width: 100%"
          v-loading="loading">
          <el-table-column :label="$t('order.order_info')" width="400">
            <template #default="scope">
              <div class="order-code" v-if="scope.row.isTopRow">
                <span class="state-text" :class="{ 'state-text-red': scope.row.orderSource != 10 }">{{
                  scope.row.orderSourceText }}</span>
                <span class="c_main">{{ $t('order.order_number_display', { place1: scope.row.orderNo }) }}</span>
                <span class="pl16">{{ $t('order.order_time_display', { place1: scope.row.createTime }) }}</span>
                <!--是否取消申请中-->
                <span class="pl16" v-if="scope.row.orderStatus == 21"><el-tag effect="dark" size="mini">{{
                  $t('order.cancel_requesting') }}</el-tag></span>
              </div>
              <template v-else>
                <div class="product-info" v-for="(item, index) in scope.row.productList" :key="index">
                  <div class="pic">
                    <img v-img-url="item.imagePath" alt="" />
                  </div>
                  <div class="info">
                    <div class="name gray3 product-name">
                      <span>{{ item.productName }}</span>
                    </div>
                    <div class="gray9" v-if="item.productAttr">
                      {{ item.productAttr }}
                    </div>
                    <div class="orange" v-if="item.refund">
                      {{ item.refund.type.text }}-{{ item.refund.status.text }}
                    </div>
                    <div class="red" v-if="scope.row.isDelete == 1"> {{ $t('order.user_deleted') }}

                    </div>
                  </div>
                  <div class="d-c-c d-c">
                    <div class="orange">￥ {{ item.productPrice }}</div>
                    <div class="gray3">x{{ item.totalNum }}</div>
                  </div>
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="pay_price" :label="$t('order.payment_amount')" show-overflow-tooltip>
            <template #default="{ row }">
              <!-- <div v-if="!scope.row.isTopRow">
              <div class="orange">{{ scope.row.payPrice }}</div>
              <p class="gray9">(含运费：{{ scope.row.expressPrice }})</p>
              </div> -->
              <div v-if="!row.isTopRow">
                <template v-if="row.orderSource == 80">
                  <p class="orange">{{ $t('order.deposit_display', { place1: row.money }) }}</p>
                  <p class="orange">{{ $t('order.final_payment_display', { place1: row.balancePayment }) }}</p>
                </template>
                <div class="orange" v-else>
                  {{ row.payPrice }}
                </div>
                <p class="gray9">{{ $t('order.freight_display', { place1: row.expressPrice }) }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" :label="$t('order.buyer')">
            <template #default="scope">
              <div v-if="!scope.row.isTopRow">
                <div>{{ scope.row.nickName }}</div>
                <div class="gray9">ID：({{ scope.row.userId }})</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" :label="$t('order.merchant_name0')"></el-table-column>
          <el-table-column :label="$t('order.transaction_status')">
            <template #default="scope">
              <div v-if="!scope.row.isTopRow">
                {{ scope.row.orderStatusText }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="pay_type.text" :label="$t('order.payment_method')">
            <template #default="scope">
              <div v-if="!scope.row.isTopRow">
                <span class="gray9">{{ scope.row.payTypeText }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="delivery_type.text" :label="$t('order.delivery_method')">
            <template #default="scope">
              <div v-if="!scope.row.isTopRow">
                <span class="green">{{ scope.row.deliveryTypeText }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('order.evaluation')" width="60">
            <template #default="scope">
              <div v-if="!scope.row.isTopRow">
                <span v-if="scope.row.isComment == 0">{{ $t('order.not_evaluated') }}</span>
                <span v-else="">{{ $t('order.evaluated') }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('order.shopremak')" prop="shopRemark"></el-table-column>
          <el-table-column fixed="right" :label="$t('order.action')" width="100">
            <template #default="scope">

              <div v-if="!scope.row.isTopRow">

                <el-button @click="addClick(scope.row)" type="text" size="small" v-auth="'/order/order/detail'">{{
                  $t('order.details') }}</el-button>
                <el-button v-if="
                  scope.row.deliveryType == 10 &&
                  scope.row.deliveryStatus == 20
                " @click="getLogistics(scope.row)" link type="primary" size="small" v-auth="'/order/order/express'">{{
                  $t('order.view_logistics') }}
                </el-button>
                <el-button type="text" size="small" @click="selectItem(scope.row)">{{$t('order.remark')}}</el-button>
                <!--              <el-button
                v-if="scope.row.payStatus == 20 && scope.row.deliveryStatus == 10 && scope.row.orderStatus != 20 && scope.row.orderStatus != 21 && scope.row.deliveryType == 10"
                @click="addClick(scope.row)"
                type="text"
                size="small"
                v-auth="'/order/order/delivery'"
              >
                发货
              </el-button>

              <el-button
                v-if="scope.row.payStatus == 20 && scope.row.deliveryStatus == 10 && scope.row.orderStatus != 20 && scope.row.orderStatus != 21 && scope.row.deliveryType == 20"
                @click="addClick(scope.row)"
                type="text"
                size="small"
                v-auth="'/order/operate/extract'"
              >
                核销
              </el-button>
              <el-button
                v-if="scope.row.payStatus == 20 && scope.row.deliveryStatus == 10 && scope.row.orderStatus != 20 && scope.row.orderStatus != 21 && scope.row.deliveryType == 30"
                @click="addClick(scope.row)"
                type="text"
                size="small"
                v-auth="'/order/order/delivery'"
              >
                发货
              </el-button>
              <el-button
                v-if="scope.row.payStatus == 20 && scope.row.deliveryStatus == 10 && scope.row.orderStatus == 10"
                @click="cancelClick(scope.row)"
                type="text"
                size="small"
                v-auth="'/order/operate/confirmCancel'"
              >
                取消
              </el-button>
              <el-button v-if="scope.row.orderStatus == 21" @click="addClick(scope.row)" type="text" size="small" v-auth="'/order/operate/confirmCancel'">审核</el-button> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
          :current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper"
          :total="totalDataNumber"></el-pagination>
      </div>
    </div>
    <Logistics v-if="isLogistics" :logisticsData="logisticsData" :isLogistics="isLogistics"
      @closeDialog="closeLogistics">
    </Logistics>
    <el-dialog :title="$t('order.batch_shipping_note')" v-model="dialogBatchDelivery" width="30%">
      <div>{{ $t('order.batch_step_1') }}</div>
      <div> {{ $t('order.batch_step_2') }}

      </div>
      <div> {{ $t('order.batch_step_3') }}

        <el-link type="primary" :underline="false" @click="gotoExpress()">{{ $t('order.view') }}</el-link>
      </div>
      <div style="padding-top: 20px; padding-bottom: 20px; text-align: center">
        <el-upload class="avatar-uploader" ref="upload" action="string"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          :before-upload="onBeforeUploadImage" :http-request="UploadImage" :show-file-list="false">
          <el-button size="small" icon="Upload" type="primary">{{ $t('order.upload_shipping_template') }}</el-button>
        </el-upload>
      </div>
    </el-dialog>
    <!--处理-->
    <Cancel v-if="open_edit" :open_edit="open_edit" :order_no="order_no" @closeDialog="closeDialogFunc($event, 'edit')">
    </Cancel>
    <el-dialog :title="$t('order.shopremak')" v-model="remarkShow" width="30%">
      <el-input type="textarea" v-model="remark" :placeholder="$t('order.input_remark')"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="remarkShow = false">{{$t('order.cancel')}}</el-button>
          <el-button type="primary" @click="updateRemark">
            {{$t('order.confirm')}}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import OrderApi from "@/api/order.js";
import qs from "qs";
import Cancel from "./dialog/cancel.vue";
import { useUserStore } from "@/store";
import Logistics from "@/components/logistics/viewLogistics.vue";
const {
  token
} = useUserStore();
export default {
  components: {
    Cancel,
    Logistics
  },
  data() {
    return {
      token,
      /*切换菜单*/
      activeName: "all",
      /*是否加载完成*/
      loading: true,
      /*列表数据*/
      tableData: [],
      /*一页多少条*/
      pageSize: 10,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*横向表单数据模型*/
      searchForm: {
        search: "",
        orderNo: "",
        style_id: "",
        store_id: "",
        createTime: "",
        orderSource: ""
      },
      /*配送方式*/
      exStyle: [],
      /*门店列表*/
      shopList: [],
      /*时间*/
      create_time: "",
      /*统计*/
      order_count: {
        payment: 0,
        delivery: 0,
        received: 0,
        comment: 0,
        six: 0,
        cancel: 0,
        cancelApply: 0,
        delete: 0
      },
      dialogBatchDelivery: false,
      /*是否打开编辑弹窗*/
      open_edit: false,
      logisticsData: {},
      isLogistics: false,
      /*当前编辑的对象*/
      order_no: "",
      supplierList: [],
      orderSourceList: [],
      remarkShow: false,
      remark: '',
      activeItem: {}
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    getLogistics(row) {
      let self = this;
      let Params = {
        orderId: row.orderId,
        expressId: row.expressId,
        expressNo: row.expressNo
      };
      self.loading = true;
      OrderApi.orderExpress(Params, true).then(res => {
        self.loading = false;
        self.logisticsData = res.data.express.data;
        console.log(self.logisticsData);
        self.openLogistics();
      }).catch(error => {
        self.loading = false;
      });
    },
    openLogistics() {
      this.isLogistics = true;
      console.log(this.isLogistics);
    },
    closeLogistics() {
      this.isLogistics = false;
    },
    /*跨多列*/
    arraySpanMethod(row) {
      if (row.rowIndex % 2 == 0) {
        if (row.columnIndex === 0) {
          return [1, 8];
        }
      }
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.curPage = val;
      self.getData();
    },
    /*每页多少条*/
    handleSizeChange(val) {
      this.curPage = 1;
      this.pageSize = val;
      this.getData();
    },
    /*切换菜单*/
    handleClick(tab, event) {
      let self = this;
      self.curPage = 1;
      self.getData();
    },
    /*获取列表*/
    getData() {
      let self = this;
      let search = this.searchForm;
      let Params = {};
      Params.dataType = self.activeName;
      Params.pageIndex = self.curPage;
      Params.pageSize = self.pageSize;
      if (search.createTime && search.createTime.length > 1) {
        Params.startDate = search.createTime[0];
        Params.endDate = search.createTime[1];
      }
      Params.orderNo = search.orderNo;
      Params.shopSupplierId = search.shopSupplierId;
      Params.search = search.search;
      Params.deliveryType = search.style_id;
      Params.orderSource = search.orderSource;
      self.loading = true;
      OrderApi.orderlist(Params, true).then(res => {
        let list = [];
        for (let i = 0; i < res.data.orderList.records.length; i++) {
          let item = res.data.orderList.records[i];
          let topitem = {
            orderNo: item.orderNo,
            createTime: item.createTime,
            orderSource: item.orderSource,
            orderSourceText: item.orderSourceText,
            orderStatus: item.orderStatus,
            isTopRow: true
          };
          list.push(topitem);
          list.push(item);
        }
        self.tableData.data = list;
        self.orderSourceList = res.data.orderSource;
        self.totalDataNumber = res.data.orderList.total;
        self.exStyle = res.data.deliveryList;
        self.supplierList = res.data.supplierList;
        self.order_count = res.data.orderCount;
        self.loading = false;
      }).catch(error => { });
    },
    selectItem(item) {
      this.activeItem = item,
        this.remarkShow = true
    },
    updateRemark() {
      OrderApi.updateRemark({
        orderId: this.activeItem.orderId,
        shopRemark: this.remark,
      }, true).then(res => {
        this.getData();
      }).finally(() => {
        this.remarkShow = false
      })
    },
    /*打开取消*/
    cancelClick(item) {
      this.order_no = item.orderNo;
      this.open_edit = true;
    },
    /*关闭弹窗*/
    closeDialogFunc(e, f) {
      if (f == "edit") {
        this.open_edit = e.openDialog;
        if (e.type == "success") {
          this.getData();
        }
      }
    },
    /*打开添加*/
    addClick(row) {
      let self = this;
      let params = row.orderId;
      self.$router.push({
        path: "/order/order/Detail",
        query: {
          orderId: params
        }
      });
    },
    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.tableData = [];
      this.getData();
    },
    onExport: function () {
      let self = this;
      let search = this.searchForm;
      let Params = {};
      Params.dataType = self.activeName;
      if (search.createTime && search.createTime.length > 1) {
        Params.startDate = search.createTime[0];
        Params.endDate = search.createTime[1];
      }
      Params.orderSource = search.orderSource;
      Params.orderNo = search.orderNo;
      Params.deliveryType = search.style_id;
      Params.shopSupplierId = search.shopSupplierId;
      Params.search = search.search;
      Params.tokenshop = self.token;
      let baseUrl = import.meta.env.VITE_BASIC_URL;
      console.log("baseUrl", baseUrl);
      if (!baseUrl) {
        baseUrl = window.location.protocol + "//" + window.location.host;
      }
      //let baseUrl = "http://127.0.0.1:8890";
      window.location.href = baseUrl + "/api/shop/order/operate/export?" + qs.stringify(Params);
    },
    // 显示批量发货说明
    showBatchDelivery() {
      this.dialogBatchDelivery = true;
    },
    /*跳转物流公司*/
    gotoExpress() {
      let self = this;
      self.$router.push("/setting/express/index");
    },
    /*选择图片之前*/
    onBeforeUploadImage(file) {
      var fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isEXCEL = fileType === "xlsx";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isEXCEL) {
        ElMessage.error($t("order.file_format_limit"));
      }
      if (!isLt10M) {
        ElMessage.error($t("order.file_size_limit"));
      }
      return isEXCEL && isLt10M;
    },
    /*上传图片*/
    UploadImage(param) {
      let self = this;
      const loading = ElLoading.service({
        lock: true,
        text: $t("order.processing_wait"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const formData = new FormData();
      formData.append("iFile", param.file);
      OrderApi.batchDelivery(formData).then(response => {
        loading.close();
        self.dialogBatchDelivery = false;
        ElMessage({
          message: response.msg,
          type: "warning"
        });
      }).catch(response => {
        loading.close();
        ElMessage({
          message: $t("order.processing_failed"),
          type: "warning"
        });
        param.onError();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.product-info {
  padding: 10px 0;
  border-top: 1px solid #eeeeee;
}

.order-code .state-text {
  padding: 2px 4px;
  border-radius: 4px;
  background: #808080;
  color: #ffffff;
}

.order-code .state-text-red {
  background: red;
}

.table-wrap .product-info:first-of-type {
  border-top: none;
}

.table-wrap .el-table__body tbody .el-table__row:nth-child(odd) {
  background: #f5f7fa;
}
</style>
